<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>添加API</title>
		<meta name="renderer" content="webkit">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
		<link rel="stylesheet" href="../../../css/font.css">
		<link rel="stylesheet" href="../../../css/weadmin.css">
		<!-- 让IE8/9支持媒体查询，从而兼容栅格 -->
		<!--[if lt IE 9]>
	      <script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
	      <script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
	    <![endif]-->
	    <script src="../../../js/jquery-3.1.1.js"></script>
	    <style type="text/css">
	    	.yf-input-del .layui-input-inline .layui-input {
				padding-right: 20px;
			}

			.yf-input-del .layui-input-inline i.layui-icon {
				position: absolute;
				right: 2px;
				top: 10px;
				color: #999999;
			}
	    </style>
	</head>

	<body>
		<div class="weadmin-body">
			<div class="layui-row" id="apiTypeselect">
				<form class="layui-form layui-col-md12 we-search">
					<div class="layui-input-inline">
						<select name="cateid" id="node_ip">

						</select>
					</div>
					<div class="layui-inline">
						<input type="text" name="keyword" placeholder="请输入名称" autocomplete="off" class="layui-input">
					</div>
					<button class="layui-btn" lay-submit="" lay-filter="sreach"><i class="layui-icon">&#xe615;</i></button>
				</form>
			</div>
			<div>
					<table class="layui-table" id="idTest">
							<thead id = "table_resource_header">
								<tr>
									<th>ID</th>
									<th>名称</th>
									<th>url</th>
									<th>访问方式</th>
									<th>状态</th>
								</tr>
							</thead>
							<tbody id ="table_resource_list">
							</tbody>
					</table>
					<div class="layui-input-inline">
						<div id = "page">
						</div>
						<button class="layui-btn" lay-filter="add" lay-submit="" onclick="confirm()">确定</button>
					</div>
				</div>
		</div>
		<script src="../../../lib/layui/layui.js" charset="utf-8"></script>
 		<script type="text/javascript">
				var curSourceType;//当前页面需要加载的资源类型： "api"、"menue"、"user"
				var apiTypeId;//Api类型id
				var curRoleId;
				var curResourceId;
			$(function(){
				
				layui.use(['form', 'jquery','util','admin', 'layer'], function() {
					var form = layui.form,
						$ = layui.jquery,
						util = layui.util,
						admin = layui.admin,
						layer = layui.layer;
					
					//自定义验证规则
					form.verify({
						pid: [/^[0-9a-zA-Z]{4}$/, '必须为字母或数字且长度为4'],
						intVal: [ /^[0-9]+[0-9]*]*$/, '必须为正整数'],
						allIntVal: [ /^-?[1-9]\d*$/, '必须为整数']
					});
					form.on('select', function (data) {
						//console.log(data.value)
						apiTypeId = data.value;
						getApiByItemId(data.value+"="+curRoleId,1,10,true);
					});
					//失去焦点时判断值为空不验证，一旦填写必须验证

				});
				
				curSourceType = parent.sourceType;
				curRoleId=parent.curSelectRoleId;

				if(curSourceType == "api"){
					getAPIListByRoleId(curRoleId,1,10,true);
					getApiType();

				}else if(curSourceType == "menue"){
					$("#apiTypeselect").html("")
					getMenueListByRoleId(curRoleId,1,10,true);
				}else if(curSourceType == "user"){
					$("#apiTypeselect").html("")//清空下拉框
					getUserListByRoleId(curRoleId,1,10,true);
				}
			})
		</script>
		<script>
		//获取API类型
		function getApiType(){
			var userInfo = localStorage.getItem("userInfo")
			var user = JSON.parse(userInfo);
			var jwt = user.jwt;
			$.post("/inner/api/initApiType",{"jwt":jwt,"userId":user.user.uid,str:false},function(data){
				if(data.retSig == 200){

					var retData = data.httpRet;//目前未分页，因此没有list
					var str = "";
					for(var i=0;i<retData.length;i++){
						var iotGateDB = retData[i];
						str +="<option value='" + iotGateDB.id + "'>"+iotGateDB.name+"</option>";
					}
					if(str != ""){
						str = "<option value='-1'> 全部 </option>"+str;
					}
					$('#node_ip').html(str);
					layui.form.render();
				}
			});

		}
		function confirm(){
			;
			if(curResourceId==""){
				layer.msg('请选择一条数据!', {
					icon: 4,
					time: 1000
				});
				return;
			}

			var userInfo = localStorage.getItem("userInfo")
			var user = JSON.parse(userInfo);
			var jwt = user.jwt;
			var url;
			if(curSourceType == "api" || curSourceType == "menue"){
				url="/inner/role/authorityRoleResource";
			}else if(curSourceType == "user"){
				url="/inner/role/authorityRoleUser";
			}
			$.post(url, {"data":{"roleId":curRoleId,"resourceId":curResourceId},"jwt":jwt,"userId":user.user.uid},
				function(data){
					if(data.retSig == 200){ // 201表示已经存在
						var index = parent.layer.getFrameIndex(window.name);
						
						var _len = parent.$('#memberList tr').length;
						//调用父页面的初始化方法
						curSourceType = parent.sourceType;
						curRoleId=parent.curSelectRoleId;
						;
						if(curSourceType == "api"){
							parent.getAPIListByRoleId(curRoleId,1,10,true);
						}else if(curSourceType == "menue"){
							parent.getMenueListByRoleId(curRoleId,1,10,true);
						}else if(curSourceType == "user"){
							parent.getUserListByRoleId(curRoleId,1,10,true);
						}
						//parent.getAllRoles();
						//关闭当前frame
						parent.layer.close(index);
						
						
					}else if(data.retSig == 201){
						layer.msg("角色已经存在",{icon: 5,time: 2000});
					}
			});
			
		}
		function selectThis(th,resourceId){
			curResourceId = resourceId;
			$(".layui-form-checkbox").removeClass('layui-form-checked');
			if($(th).hasClass('layui-form-checked')) {
				$(th).removeClass('layui-form-checked');
				if($(th).hasClass('header')) {
					$(".layui-form-checkbox").removeClass('layui-form-checked');
				}
			} else {
				$(th).addClass('layui-form-checked');
				if($(th).hasClass('header')) {
					$(".layui-form-checkbox").addClass('layui-form-checked');
				}
			}
		}
		
		function getAPIListByRoleId(roleId,pageIndex,pageSize,isFirstLoad){
			//表头
			var str1 = 
				"<tr>"+
				'<th>'+
				'<div class="layui-unselect layui-form-checkbox" lay-skin="primary"><i class="layui-icon">&#xe605;</i></div>'+
			'</th>'+
					"<th>名称</th>"+
					"<th>url</th>"+
					"<th>访问方式</th>"+
					"<th>版本</th>"+
					"<th>状态</th>"+
				"</tr>";
			$('#table_resource_header').html(str1);
			$('#table_resource_list').html("");
			var userInfo = localStorage.getItem("userInfo")
			var user = JSON.parse(userInfo);
			var jwt = user.jwt;
			$.post("/inner/role/getRestApiByRoleId",{"jwt":jwt,"userId":user.user.uid,"str":roleId,"pageIndex":pageIndex,"pageSize":pageSize},function(data){
				if(data.retSig == 200){

					var retData = data.httpRet.list;
					var str = "";
					for(var i=0;i<retData.length;i++){
						var roleInfo = retData[i];

						str +=
						'<tr data-id="' + roleInfo.id + '">' +
						'<td>'+
						'<div class="layui-unselect layui-form-checkbox" onclick="selectThis(this,\'' + roleInfo.id + '\')" lay-skin="primary" data-id="' + roleInfo.id + '"><i class="layui-icon">&#xe605;</i></div>'+
					'</td>'+
							'<td title="'+roleInfo.name+'">' + (roleInfo.name.length >5 ? roleInfo.name.substring(0,5)+"..." :  roleInfo.name) + '</td>'+
							'<td>' + roleInfo.uri + '</td>'+
							'<td>' + roleInfo.method + '</td>'+
							'<td>' + roleInfo.version + '</td>'+
							'<td>'+(roleInfo.status == 1 ? "正常" : "禁用")+'</td>'+
						'</tr>'	;
					}
					var total = 0;
					total = data.httpRet.total;
					//$("#sourceNum").html("资源总数"+data.httpRet.data.data.total+"条")
					$('#table_resource_list').html(str);
					if(isFirstLoad){
						
						layui.use('laypage', function(){
							  var laypage = layui.laypage;
							  
							  //执行一个laypage实例
							  laypage.render({
							    elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
							    ,count: total //数据总数，从服务端得到
							    ,layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh']
							    ,jump: function(obj, first){
							        //obj包含了当前分页的所有参数，比如：
							        //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
							        //console.log(obj.limit); //得到每页显示的条数
							        //首次不执行

							        if(!first){
							        	getAPIListByRoleId(roleId,obj.curr,obj.limit,false);//翻页的时候不重新加载
							        }else{
							        	
							        }
							      }
							  });
						});
					}
					layui.form.render();
				}
			});
		}
		//获取当前角色下，制定api结合下未关联过的API
		function getApiByItemId(itemId,pageIndex,pageSize,initLaypage){
			//表头
			var str1 =
					"<tr>"+
					'<th>'+
					'<div class="layui-unselect layui-form-checkbox" lay-skin="primary"><i class="layui-icon">&#xe605;</i></div>'+
					'</th>'+
					"<th>名称</th>"+
					"<th>url</th>"+
					"<th>访问方式</th>"+
					"<th>版本</th>"+
					"<th>状态</th>"+
					"</tr>";
			$('#table_resource_header').html(str1);
			$('#table_resource_list').html("");
			var userInfo = localStorage.getItem("userInfo")
			var user = JSON.parse(userInfo);
			var jwt = user.jwt;
			$.post("/inner/api/initApiByItemIdAndRID",{"jwt":jwt,"userId":user.user.uid,"str":itemId,"pageIndex":pageIndex,"pageSize":pageSize},function(data){
				if(data.retSig == 200){

					// var retData = data.httpRet.list;
					// var str = "";
					// for(var i=0;i<retData.length;i++){
					// 	var iotGateDB = retData[i];
					// 	str +=
					// 			'<tr data-id="' + iotGateDB.pId + '">' +
					// 			/* '<td>'+
                    //                 '<div class="layui-unselect layui-form-checkbox" lay-skin="primary" data-id="' + iotGateDB.id + '"><i class="layui-icon">&#xe605;</i></div>'+
                    //             '</td>'+ */
					// 			'<td>' + iotGateDB.id + '</td>'+
					// 			'<td title="'+iotGateDB.name+'">' + (iotGateDB.name.length > 5 ? iotGateDB.name.substring(0,5)+"..." :  iotGateDB.name) + '</td>'+
					// 			'<td>'+(iotGateDB.needAuth == 0 ? "否"  : "是")+'</td>'+
					// 			'<td>'+(iotGateDB.uri == null ? "" :iotGateDB.uri ) +'</td>'+
					// 			'<td>'+ (iotGateDB.method == null ? "" : iotGateDB.method ) +'</td>'+
					// 			'<td>'+ (iotGateDB.version  == null ? "" : iotGateDB.version )+'</td>'+
					// 			'<td>'+(iotGateDB.status == 1 ? "正常" : "禁用 ")+'</td>'+
					// 			'<td class="td-manage" style="text-align:center;">'+
					// 			'<a title="编辑" onclick="updateStrategy(this,\'' + iotGateDB.id + '\')" href="javascript:;" style="margin-right:10px;"><i class="layui-icon">&#xe642;</i></a>'+
					// 			'<a title="删除" onclick="delStrategy(this,\'' + iotGateDB.id + '\')" href="javascript:;"><i class="layui-icon">&#xe640;</i></a>'+
					// 			'</td>'+
					// 			'</tr>'	;
					// }
					// var total = data.httpRet.total;
					// $("#strategy_total").html("总数"+total+"条")
					// $('#table_brian').html(str);

					var retData = data.httpRet.list;
					var str = "";
					for(var i=0;i<retData.length;i++){
						var roleInfo = retData[i];

						str +=
								'<tr data-id="' + roleInfo.id + '">' +
								'<td>'+
								'<div class="layui-unselect layui-form-checkbox" onclick="selectThis(this,\'' + roleInfo.id + '\')" lay-skin="primary" data-id="' + roleInfo.id + '"><i class="layui-icon">&#xe605;</i></div>'+
								'</td>'+
								'<td title="'+roleInfo.name+'">' + (roleInfo.name.length >5 ? roleInfo.name.substring(0,5)+"..." :  roleInfo.name) + '</td>'+
								'<td>' + roleInfo.uri + '</td>'+
								'<td>' + roleInfo.method + '</td>'+
								'<td>' + roleInfo.version + '</td>'+
								'<td>'+(roleInfo.status == 1 ? "正常" : "禁用")+'</td>'+
								'</tr>'	;
					}
					var total = 0;
					total = data.httpRet.total;
					//$("#sourceNum").html("资源总数"+data.httpRet.data.data.total+"条")
					$('#table_resource_list').html(str);


					if(initLaypage){
						layui.use('laypage', function(){
							var laypage = layui.laypage;

							//执行一个laypage实例
							laypage.render({
								elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
								,count: total //数据总数，从服务端得到
								,layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
								,jump: function(obj, first){
									//obj包含了当前分页的所有参数，比如：
									//console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
									//console.log(obj.limit); //得到每页显示的条数
									//首次不执行

									if(!first){
										getApiByItemId(itemId,obj.curr,obj.limit,false);//翻页的时候不重新加载
									}else{

									}
								}
							});
						});
					}
				}
			});

		}
		function getMenueListByRoleId(roleId,pageIndex,pageSize,isFirstLoad){
			//表头
			var str1 = 
				"<tr>"+
				'<td>'+
				'<div class="layui-unselect layui-form-checkbox" lay-skin="primary"><i class="layui-icon">&#xe605;</i></div>'+
			'</td>'+
				"<th>ID</th>"+
					"<th>名称</th>"+
					"<th>编码</th>"+
					"<th>url</th>"+
					"<th>状态</th>"+
				"</tr>";
			$('#table_resource_header').html(str1);
			$('#table_resource_list').html("");
			var userInfo = localStorage.getItem("userInfo")
			var user = JSON.parse(userInfo);
			var jwt = user.jwt;
			$.post("/inner/role/getMenusExtendByRoleId",{"jwt":jwt,"userId":user.user.uid,"str":roleId,"pageIndex":pageIndex,"pageSize":pageSize},function(data){
				if(data.retSig == 200){

					var retData = data.httpRet.list;
					var str = "";
					for(var i=0;i<retData.length;i++){
						var roleInfo = retData[i];

						str +=
						'<tr data-id="' + roleInfo.id + '">' +
						'<td>'+
						'<div class="layui-unselect layui-form-checkbox" onclick="selectThis(this,\'' + roleInfo.id + '\')" lay-skin="primary" data-id="' + roleInfo.id + '"><i class="layui-icon">&#xe605;</i></div>'+
					'</td>'+
							'<td>'+roleInfo.id+'</td>'+
							'<td>'+roleInfo.name+'</td>'+
							'<td>'+roleInfo.code+'</td>'+
							'<td>' + roleInfo.uri + '</td>'+
							
							'<td>'+(roleInfo.status == 1 ? "正常" : "禁用")+'</td>'+
						'</tr>'	;
					}
					var total = 0;
					total = data.httpRet.total;
					
					//$("#sourceNum").html("资源总数"+data.httpRet.data.data.total+"条")
					$('#table_resource_list').html(str);
					if(isFirstLoad){
						
						layui.use('laypage', function(){
							  var laypage = layui.laypage;
							  
							  //执行一个laypage实例
							  laypage.render({
							    elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
							    ,count: total //数据总数，从服务端得到
							    ,layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh']
							    ,jump: function(obj, first){
							        //obj包含了当前分页的所有参数，比如：
							        //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
							        //console.log(obj.limit); //得到每页显示的条数
							        //首次不执行

							        if(!first){
							        	getMenueListByRoleId(roleId,obj.curr,obj.limit,false);//翻页的时候不重新加载
							        }else{
							        	
							        }
							      }
							  });
						});
					}
					layui.form.render();
				}
			});
		}
		function getUserListByRoleId(roleId,pageIndex,pageSize,isFirstLoad){
			//表头
			var str1 = 
				"<tr>"+
				'<td>'+
				'<div class="layui-unselect layui-form-checkbox" lay-skin="primary"><i class="layui-icon">&#xe605;</i></div>'+
			'</td>'+
				"<th>UID</th>"+
					"<th>名称</th>"+
					"<th>电话</th>"+
					"<th>邮箱</th>"+
					"<th>状态</th>"+
				"</tr>";
			$('#table_resource_header').html(str1);
			$('#table_resource_list').html("");
			var userInfo = localStorage.getItem("userInfo")
			var user = JSON.parse(userInfo);
			var jwt = user.jwt;
			$.post("/inner/role/getUserListExtendByRoleId",{"jwt":jwt,"userId":user.user.uid,"str":roleId,"pageIndex":pageIndex,"pageSize":pageSize},function(data){
				if(data.retSig == 200){

					var retData = data.httpRet.list;
					var str = "";
					for(var i=0;i<retData.length;i++){
						var roleInfo = retData[i];

						str +=
						'<tr data-id="' + roleInfo.uid + '">' +
						'<td>'+
						'<div class="layui-unselect layui-form-checkbox" onclick="selectThis(this,\'' + roleInfo.uid + '\')" lay-skin="primary" data-id="' + roleInfo.id + '"><i class="layui-icon">&#xe605;</i></div>'+
					'</td>'+
							'<td>' + roleInfo.uid + '</td>'+
							'<td>'+roleInfo.username+'</td>'+
							'<td>'+roleInfo.phone+'</td>'+
							'<td>'+roleInfo.email+'</td>'+
							'<td>'+(roleInfo.status == 1 ? "正常" : "禁用")+'</td>'+
						'</tr>'	;
					}
					var total = 0;
					total = data.httpRet.total;
					
					//$("#sourceNum").html("资源总数"+data.httpRet.data.data.total+"条")
					$('#table_resource_list').html(str);
					if(isFirstLoad){
						
						layui.use('laypage', function(){
							  var laypage = layui.laypage;
							  
							  //执行一个laypage实例
							  laypage.render({
							    elem: 'page' //注意，这里的 test1 是 ID，不用加 # 号
							    ,count: total //数据总数，从服务端得到
							    ,layout: [ 'count', 'prev', 'page', 'next', 'limit', 'refresh']
							    ,jump: function(obj, first){
							        //obj包含了当前分页的所有参数，比如：
							        //console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
							        //console.log(obj.limit); //得到每页显示的条数
							        //首次不执行

							        if(!first){
							        	getUserListByRoleId(roleId,obj.curr,obj.limit,false);//翻页的时候不重新加载
							        }else{
							        	
							        }
							      }
							  });
						});
					}
					layui.form.render();
				}
			});
		}
			layui.extend({
				admin: '{/}../../../js/admin'
			});
			
		</script>
	</body>

</html>